<?php
/**
 * Plugin Name: 栖岛账号登录
 * Plugin URI: https://web.tvcloud.top/
 * Description: 支持使用栖岛账号登录WordPress网站，实现快速登录和账号绑定
 * Version: 1.0.0
 * Author: 艺当然
 * Author URI: https://web.tvcloud.top/
 * License: Proprietary
 * Text Domain: qidao-connect
 */

// 如果直接访问此文件，则中止执行
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('QIDAO_CONNECT_VERSION', '1.0.0');
define('QIDAO_CONNECT_PATH', plugin_dir_path(__FILE__));
define('QIDAO_CONNECT_URL', plugin_dir_url(__FILE__));
define('QIDAO_CONNECT_BASENAME', plugin_basename(__FILE__));

// 加载必要的文件
require_once QIDAO_CONNECT_PATH . 'includes/class-qidao-connect.php';
require_once QIDAO_CONNECT_PATH . 'includes/functions.php';
require_once QIDAO_CONNECT_PATH . 'includes/class-qidao-connect-profile.php';

// 初始化插件
function qidao_connect_init() {
    // 实例化主类
    $qidao_connect = new Qidao_Connect();
    $qidao_connect->init();
    
    // 实例化个人资料页面类
    $qidao_connect_profile = new Qidao_Connect_Profile();
}
add_action('plugins_loaded', 'qidao_connect_init');

// 插件激活时执行
register_activation_hook(__FILE__, 'qidao_connect_activate');
function qidao_connect_activate() {
    // 创建数据表
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'qidao_connect';

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        user_id bigint(20) NOT NULL,
        openid varchar(50) NOT NULL,
        access_token varchar(255) NOT NULL,
        refresh_token varchar(255) NOT NULL,
        expires_in int(11) NOT NULL,
        datetime datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        name varchar(50) NOT NULL,
        nickname varchar(50) NOT NULL,
        gender tinyint(1) NOT NULL DEFAULT 0,
        head_img varchar(255) NOT NULL,
        PRIMARY KEY  (id),
        KEY user_id (user_id),
        KEY openid (openid)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 添加版本号到数据库
    add_option('qidao_connect_version', QIDAO_CONNECT_VERSION);
    
    // 添加重写规则
    add_rewrite_rule('^qidao-oauth/?$', 'index.php?qidao_action=oauth', 'top');
    add_rewrite_rule('^qidao-callback/?$', 'index.php?qidao_action=callback', 'top');
    
    // 刷新重写规则
    flush_rewrite_rules();
}

// 插件卸载时执行
register_deactivation_hook(__FILE__, 'qidao_connect_deactivate');
function qidao_connect_deactivate() {
    // 清理临时数据
    delete_option('qidao_connect_temp_data');
}

// 插件卸载时执行
register_uninstall_hook(__FILE__, 'qidao_connect_uninstall');
function qidao_connect_uninstall() {
    // 删除数据表和选项
    global $wpdb;
    $wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}qidao_connect");
    delete_option('qidao_connect_options');
    delete_option('qidao_connect_version');
} 